package simorg.view;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import simorg.actions.Action;
import simorg.util.XslTransformer;

/**
 * Servlet implementation class DispatchServlet
 */
public class DispatchServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public DispatchServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		WebSessionContext wc = new WebSessionContext(this, request, response);
		
		Action action = wc.getAction();
		
		try {
			ModelView mv = action.checkAccess(wc);
			if ( mv != null ) {
				// access violation
				XslTransformer.transform(wc, mv.getPageXml(), mv.getView());
				return;
			}
			mv = action.process(wc);
			if ( mv != null ) {
				wc.addViewOptions(mv.getPageXml());
				XslTransformer.transform(wc, mv.getPageXml(), mv.getView());
			}
			// otherwise a redirect was signaled.
		}
		catch (Exception e) {
			ErrorHandler eh = new ErrorHandler(action, e);
			e.printStackTrace();
			try {
				XslTransformer.transform(wc,eh.getPageXml(), Page.Error);
			} catch (Exception e1) {
				e1.printStackTrace();
			}
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}
